<?php
function get_feeds($approved=1) {
	return mysql_array(mysql_select("feeds",array("approved"=>$approved)));
}

function get_pending_feeds() {
	return get_feeds('0');
}

function approve_feed($id) {
	return mysql_update("feeds",array("approved"=>1),array("id"=>$id));
}

function remove_feed($id) {
	return mysql_remove("feeds",array("id"=>$id));
}

function get_feed($id) {
	return mysql_row_array(mysql_select("feeds",array("id"=>$id)));
}

function add_feed_event($UID,$feed,$title,$startdate,$starttime,$enddate,$endtime,$desc) {
	$allday=0;
	if (!$starttime) $allday = 1;
	if (mysql_exists("events_feeds",array("UID"=>$UID))) {
		$data = mysql_row_array(mysql_select("events_feeds",array("UID"=>$UID)));
		$id = $data['event'];
		return edit_event($id,$title,null,$feed,$allday,$startdate,$starttime,$enddate,$endtime,$desc,1);
	} else {
		$id = add_event($title,null,$allday,$startdate,$starttime,$enddate,$endtime,$desc,1);
		return mysql_insert("events_feeds",array("UID"=>$UID,"feed"=>$feed,"event"=>$id));
	}
}
 
function parse_date($date) {
	return $date['value']['year'] . "-" . $date['value']['month'] . "-" . $date['value']['day'];
}

function parse_time($time) {
	if (!isset($time['value']['hour']) && !isset($time['value']['min'])) return false;
	return $time['value']['hour'] . ":" . $time['value']['min'] . ":" . $time['value']['sec'];
}
function get_offset() {
	if (date("T") == "EST") return -5;
	return -4;
}

function parse_dt($dt) {
	$date= parse_date($dt);
	$time= parse_time($dt);
	if ($time) {
		$timestamp = strtotime(get_offset() . " hours",strtotime("$date $time"));
		$time = date("H:i:s", $timestamp);
		$date = date("Y-m-d", $timestamp);
	}
	$output = array("date"=>$date, "time"=>$time, "timestamp"=>$timestamp);
	return $output;
}


function parse_feed($id) {
	$feed = get_feed($id);
	$v = new vcalendar();
	$v->setConfig( 'url', $feed['url']);
	$v->parse();
	foreach($v->components as $event) {
		$uid = $event->uid['value'];
		$title = $event->summary['value'];
		if (strlen($feed['short_name']) > 0) $title = "[" . $feed['short_name'] . "] " . $title;
		$sdt = parse_dt($event->dtstart);
		$edt = parse_dt($event->dtend);
		$startdate = $sdt['date'];
		$enddate = $edt['date'];
		$starttime = $sdt['time'];
		$endtime = $edt['time'];
		$desc = $event->description[0]['value'];
		add_feed_event($uid,$id,$title,$startdate,$starttime,$enddate,$endtime,$desc);
	}
}

function parse_feeds() {
	foreach (get_feeds() as $feed) parse_feed($feed['id']);
}

?>